import { ref } from "vue";
import { defineStore } from "pinia";
import { ElMessage } from "element-plus";
import { getUserInfoAPI } from "@/api/user";

export const useUserStore = defineStore("user", () => {
  // 加密密码的字符
  const characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  // 保存账户密码
  const userInfo = ref({ username: "", password: "", remember: false });
  // 保存token
  const token = ref(JSON.parse(localStorage.getItem("token")) || "");
  // 当前登录账户的信息
  const account = ref();

  // 设置token
  const setToken = identity => {
    localStorage.setItem("token", JSON.stringify(identity));
    token.value = identity;
  };

  // 清除token
  const clearToken = () => {
    localStorage.removeItem("token");
    token.value = "";
  };

  // 是否记住账户密码
  const setRemember = () => {
    userInfo.value.remember = !userInfo.value.remember;
  };
  // 清除账户密码
  const clearUserInfo = () => {
    localStorage.removeItem("userInfo");
    userInfo.value.username = "";
    userInfo.value.password = "";
    userInfo.value.remember = false;
  };

  // 设置加密账户密码存入本地
  const setUserInfo = user => {
    clearUserInfo();
    userInfo.value.username = user.username;
    user.password.split("").forEach((item, i) => {
      if (typeof item === "number") item += i;
      userInfo.value.password += item + characters.charAt(Math.floor(Math.random() * characters.length));
    });
    setRemember();
    localStorage.setItem("userInfo", JSON.stringify(userInfo.value));
  };

  // 获取账户密码解密
  const getUserInfo = () => {
    userInfo.value.username = "";
    userInfo.value.password = "";
    userInfo.value.remember = false;
    if (localStorage.getItem("userInfo")) {
      const user = JSON.parse(localStorage.getItem("userInfo"));
      userInfo.value.username = user.username;
      user.password.split("").forEach((item, i) => {
        if (typeof item === "number") item -= i;
        if (i % 2 === 0) userInfo.value.password += item;
      });
      userInfo.value.remember = user.remember;
    }
  };

  // 设置账户
  // 获取当前账户信息
  const setAccount = async () => {
    const res = await getUserInfoAPI();
    if (res.code === 0) return (account.value = res.data);
    return ElMessage({ type: "error", message: res.message });
  };

  return {
    token,
    userInfo,
    account,
    setRemember,
    setToken,
    setUserInfo,
    setAccount,
    getUserInfo,
    clearToken,
    clearUserInfo,
  };
});
